package logic

import (
	"context"
	"errors"
	"fresh-box/models"
	"gorm.io/gorm"

	"fresh-box/hemarpc/hemarpc"
	"fresh-box/hemarpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddLogic {
	return &AddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddLogic) Add(in *hemarpc.AddRequest) (*hemarpc.AddResponse, error) {
	// todo: add your logic here and delete this line
	tx := models.DB.Begin()
	var findfresh models.Fresh
	tx.Where("name=?", in.Name).Find(&findfresh)
	if findfresh.ID != 0 {
		tx.Rollback()
		return nil, errors.New("当前商品已经存在，不要重复添加")
	}
	var class models.Class
	tx.Where("name=?", in.Classname).Find(&class)
	if class.ID == 0 {
		tx.Rollback()
		class = models.Class{
			Model: gorm.Model{},
			Name:  in.Classname,
		}
	}
	tx.Create(&class)
	fresh := models.Fresh{
		Model:   gorm.Model{},
		Name:    in.Name,
		Title:   in.Title,
		Price:   float64(in.Price),
		Num:     int(in.Num),
		ClassId: int(class.ID),
	}
	tx.Create(&fresh)
	return &hemarpc.AddResponse{
		Id: int64(fresh.ID),
	}, nil
}
